package com.example.itemprocessor.skipListener;

import com.example.itemprocessor.retry.CustomRetryException;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * 跳过
 *
 * @author XieYa
 */
//@Configuration
public class SkipListenerDemo {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    @Qualifier("skipItemProcess")
    private ItemProcessor<Object, Object> skipItemProcess;

    @Autowired
    @Qualifier("skipItemWriter")
    private ItemWriter<Object> skipItemWriter;

    @Autowired
    private MySkipListener mySkipListener;

    @Bean
    public Job skipListenerDemoJob() {
        return jobBuilderFactory.get("skipListenerDemoJob")
                .start(skipListenerDemoStep())
                .build();
    }

    @Bean
    public Step skipListenerDemoStep() {
        return stepBuilderFactory.get("skipListenerDemoStep")
                .chunk(10)
                .reader(reader())
                .processor(skipItemProcess)
                .writer(skipItemWriter)
                .faultTolerant()
                .skip(CustomRetryException.class)
                .skipLimit(5)
                .listener(mySkipListener)
                .build();
    }

    @Bean
    @StepScope
    public ListItemReader<String> reader() {
        List<String> items = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            items.add(String.valueOf(i));
        }
        return new ListItemReader<>(items);
    }
}
